//
// Copyright (c) 2011 Health Market Science, Inc.
//
package com.kmstech.greeting.services;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import com.kmstech.greeting.dao.GreetingDao;
import com.kmstech.greeting.entities.Greeting;

@Stateless
@Remote(GreetingService.class)
public class GreetingBean implements GreetingService {
  @EJB
  private GreetingDao _greetingDao;

  @Override
  public List<Greeting> getGreetings() {
    return _greetingDao.findAll();
  }

  @Override
  public String getGreeting(String language) {
    if (language == null) {
      
      throw new IllegalArgumentException("language must be not null");
    }
    
    Greeting greeting = _greetingDao.findByLangue(language);
    if (greeting != null) {
      return greeting.getMessage();
    }
    
    return null;
  }

  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void addGreeting(String language, String message) {
    if (language == null) {
      throw new IllegalArgumentException("language must be not null");
    }
    
    if (message == null) {
      throw new IllegalArgumentException("message must be not null");
    }
    
    Greeting greeting = _greetingDao.findByLangue(language);
    if (greeting != null) {
      greeting.setMessage(message);
      _greetingDao.update(greeting);
    }
    else {
      greeting = new Greeting(language, message);
      _greetingDao.create(greeting);
    }
  }
}
